Integer to Roman || Integer to English Words

Integer to Roman

Question

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

Analysis

罗马数字的构成方法在之前的Roman to Integer整理了

  • 由于数字大小控制在了4000以下,所以可能包含的数字组合情况较少,可以直接用数组进行枚举,能放在左侧且被减去的罗马字母只有X、I、C
  • 贪心策略,每次选取最大的可选数字从num中减去,并且加相应的罗马数字加入字符串中
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Solution {
public String intToRoman(int num) {
String[] roman=new String[]{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
int[] number=new int[]{1000,900,500,400,100,90,50,40,10,9,5,4,1};
StringBuilder result=new StringBuilder();
for(int i=0;i<number.length;i++){
while(num>=number[i]){
num-=number[i];
result.append(roman[i]);
}
}
return result.toString();
}
}

Integer to English Words

Question

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

For example,

1
2
3
123 -> "One Hundred Twenty Three"
12345 -> "Twelve Thousand Three Hundred Forty Five"
1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Analysis

Hint中已经给出提示将相应的数字三个一组分组后再进行考虑,故在对数字分组后调用辅助函数process处理将所得返回串加至result

  • 为了方便在数字的枚举数组中找到对应的数字,在num1中补一个空位代表0,在num2中补两个空位分别代表0,10
  • 对于每个单词间的空格,1000以上的数字统一末尾不加空格,而process中的数字统一在字符串首部加空格
  • process函数分为三种情况
    • num>=100: 百位hundred,由于thousand的个数也会存在上百个的情况,所以必须放在process内,且注意需要有等号
    • num\<100&&num>=20: 此时需要将十位与个位数分离,分别到num1、num2中找到加入字符串value中,同样需要注意边界条件num>=20
    • num<20: 直接到num1中找到加入字符串即可
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class Solution {
public static String numberToWords(int num) {
StringBuilder result=new StringBuilder();
if(num==0)
return "Zero";
if(num>=1000000000){
result.append(process(num/1000000000)+" "+"Billion");
num=num%1000000000;
}
if(num>=1000000){
result.append(process(num/1000000)+" "+"Million");
num=num%1000000;
}
if(num>=1000){
result.append(process(num/1000)+" "+"Thousand");
num=num%1000;
}
if(num>0){
result.append(process(num));
}
return result.toString().trim();
}
private static String process(int num) {
String[] num1=new String[]{" ","One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
String[] num2=new String[]{" "," ","Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
StringBuilder value=new StringBuilder();
if(num>=100){
int hundred=num/100;
value.append(" "+num1[hundred]+" "+"Hundred");
num=num%100;
}
if(num>=20&&num<100){
int single=num%10;
int doubledigit=num/10;
if(single!=0)
value.append(" "+num2[doubledigit]+" "+num1[single]);
else
value.append(" "+num2[doubledigit]);
}
if(num<20&&num>0)
value.append(" "+num1[num]);
return value.toString();
}
}